package com.yc.homepage.service.impl;

import com.yc.homepage.CourseInfo;
import com.yc.homepage.CourseInfosRequest;
import com.yc.homepage.dao.HomepageCourseDao;
import com.yc.homepage.entity.HomepageCourse;
import com.yc.homepage.service.ICourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * <h1>课程服务功能实现</h1>
 * @author yc112
 */
@Slf4j
@Service
public class CourseServiceImpl implements ICourseService {

    private HomepageCourseDao homepageCourseDao;

    @Autowired
    public CourseServiceImpl(HomepageCourseDao homepageCourseDao) {
        homepageCourseDao = homepageCourseDao;
    }

    @Override
    public CourseInfo getCourseInfo(Long courseId) {
        Optional<HomepageCourse> courseOptional = homepageCourseDao.findById(courseId);
        return buildCourseInfo(courseOptional.orElse(HomepageCourse.invalid()));
    }

    @Override
    public List<CourseInfo> getCourseInfos(CourseInfosRequest courseRequest) {
        if (CollectionUtils.isEmpty(courseRequest.getIds())) {
            return Collections.emptyList();
        }
       List<HomepageCourse> courses = homepageCourseDao.findAllById(courseRequest.getIds());
        return courses.stream().map(this :: buildCourseInfo).collect(Collectors.toList());
    }

    /**
     * <h2>根据数据记录构造对象信息</h2>
     * @param course
     * @return
     */
    private CourseInfo buildCourseInfo(HomepageCourse course) {
        return CourseInfo.builder()
                .id(course.getId())
                .courseName(course.getCourseName())
                .courseType(course.getCourseType() == 0 ? "免费课程" : "实战课程")
                .courseIcon(course.getCourseIcon())
                .courseIntro(course.getCourseIntro())
                .build();
    }
}
